#!/bin/bash
HOSTNAME="127.0.0.1"
PORT=3306
MYSQL_USER=yapai
MYSQL_PASSWORD=ypkj@1234
MYSQL_ROOT_PASSWORD=APkj@1234

currentHome=$(cd "$(dirname "$0")";pwd)
YAPAI_HOME=$(dirname "$currentHome")
HASH=`curl http://localhost:8700/sld/random/getReadomMd5 | sed -ne 's/{"//p' |sed -ne's/"}//p'| awk -F "[ \" ]+" '{print $NF}'`
echo "获取的服务授权密钥:"${HASH}
# openssl md5
SHOWPASS="123456"
# PASS=`printf  ${SHOWPASS} | openssl md5 | awk '{print $NF}'`
PASS=`mysql -hlocalhost -uyapai -p${MYSQL_PASSWORD} -e "use shuiliandong; select * from t_sys_user where user_name='ypkj'\G" 2>&1 | sed -n '2,$p' | grep -E 'password' | awk -F ':' '{print $2}'`
LP=`printf  ${PASS}${HASH}|openssl md5 | awk '{print $NF}'`
TOKENMSG=`curl -X POST "http://localhost:8700/sld/oauth/token?username=ypkj&password=${LP}&grant_type=password&client_id=Auth&client_secret=user123"`
TOKEN=`echo ${TOKENMSG} | grep -oE 'access_token":"[0-9a-zA-Z_.\-]+' | awk -F "[:\"]+" '{print $2}'`
#TOKEN=`echo ${TOKENMSG} | grep -E 'access_token":"[0-9a-zA-Z]+'`
LAST_TOKEN="Bearer "${TOKEN}
max_count=999999
assets=("assetssystem" "assetstype" "assets" "dept" "location")
declare -A myMap
myMap["assetssystem"]="t_asset_system"
myMap["assetstype"]="t_assetstype"
myMap["assets"]="t_assets"
myMap["location"]="t_location"
declare -A inMap
inMap["assetssystem"]="system"
inMap["assetstype"]="assetstype"
inMap["assets"]="assets"
inMap["location"]="location"
if [[ $# -gt 0 ]]
then
  unset assets
  assets=$@
fi
for item in ${assets[@]}
do
  total=`curl -H 'Authorization:'"${LAST_TOKEN}"'' 'http://localhost:8080/api/tenant/assetInfos?pageSize='"${max_count}"'&page=0&sortProperty=createdTime&sortOrder=DESC&type='"${item}"'' | jq .totalElements`
  if [ $total -gt 999999 ]
  then
    echo $item"need delete by handler"
  fi

  ddd=`curl -H 'Authorization:'"${LAST_TOKEN}"'' 'http://localhost:8080/api/tenant/assetInfos?pageSize='"${max_count}"'&page=0&sortProperty=createdTime&sortOrder=DESC&type='"${item}"'' | jq .data | jq '.[].id.id '`
  for data in ${ddd[@]}
  do
    echo ${data:1:-1}
    curl -XDELETE -H 'Authorization:'"${LAST_TOKEN}"'' 'http://localhost:8080/api/asset/'"${data:1:-1}"''
  done
  if [[ "$item" == "dept" ]]
  then
    mysql -hlocalhost -uyapai -p${MYSQL_PASSWORD} -e"use shuiliandong;delete from t_relatin_thingboard;"
    curl -si -H 'Authorization:'"${LAST_TOKEN}"'' 'http://'"${HOSTNAME}"':8700/sld/'"${item}"'/list/syn'
  else
    mysql -hlocalhost -uyapai -p${MYSQL_PASSWORD} -e"use nanshan;delete from t_relatin_thingboard where source_id in (select id from ${myMap[$item]});"
    curl -si -H 'Authorization:'"${LAST_TOKEN}"'' 'http://'"${HOSTNAME}"':8700/nanshan/'"${inMap[$item]}"'/list/syn'
  fi
done
